import threading
from time import sleep
import concurrent.futures
import time
import logging
from Determining_ad.src.Others_ad.others_log_start import others_ad_log_start
from Determining_ad.src.HaiNan_ad.hainan_log_start import hn_ad_log_start
from Determining_ad.src.Tools.find_entity import find_entity

import logging
import threading
import concurrent.futures
import time
from time import sleep

# 全局变量，用于控制日志收集
is_logging_active = True


def ad_log_thread():
    """
    启动一个线程来记录日志，支持手动停止
    :return: 一个元组，包含3个df
    """
    # logging.basicConfig(level=logging.INFO)
    global is_logging_active

    # 重置全局变量
    is_logging_active = True

    # 创建一个事件对象，用于控制日志收集的开始和结束
    stop_event = threading.Event()

    # 创建一个executor，将任务提交到线程池中执行
    with concurrent.futures.ThreadPoolExecutor() as executor:
        # 提交日志收集任务，返回future对象，这个对象监控任务状态
        future = executor.submit(find_entity, stop_event)

        try:
            # 添加用户交互，等待用户输入停止命令
            while is_logging_active:
                user_input = input(
                    "=======================================================================输入 'stop' 以结束日志收集:======================================================================\n ")
                if user_input.lower() == 'stop':
                    is_logging_active = False
                    break
                # 如果没有输入stop，就等待一段时间
                time.sleep(1)

            # 如果超过30秒或用户输入stop，停止日志收集
            stop_event.set()

            # 等待日志收集任务完成
            while not future.done():
                time.sleep(0.1)  # 短暂休眠，避免忙等待

            # 获取日志收集的结果
            entity, all_df, phone_brand = future.result(timeout=10)

            if entity == "bj":
                logging.info("非加密广告位")
                others_ad_log_start.get_entity(entity)
                ad_df = others_ad_log_start.get_ad_df(all_df)
                others_ad_log_start.get_phone_brand(phone_brand)

                collected_logs = all_df, ad_df, entity
                # logging.info(f"收集到的日志：{collected_logs}")
                return collected_logs

            elif entity == 'hn':
                logging.info("加密广告位")
                hn_ad_log_start.get_entity(entity)
                ad_df = hn_ad_log_start.get_ad_df(all_df)
                hn_ad_log_start.get_phone_brand(phone_brand)

                collected_logs = all_df, ad_df, entity
                # logging.info(f"收集到的日志：\n{ad_df.to_string()}")
                # logging.info(f"收集到的日志：\n{all_df.to_string()}")
                # logging.info(f"收集到的日志：{collected_logs}")
                return collected_logs

        except concurrent.futures.TimeoutError:
            logging.error("获取结果超时")
        except KeyboardInterrupt:
            logging.error("程序被用户中断")
        except Exception as e:
            logging.error(f"发生错误：{e}")
        finally:
            # 确保日志收集线程停止
            is_logging_active = False
            stop_event.set()
